package zheezes.eisp.collect.model.impl.gd;

import java.util.Calendar;

import org.apache.log4j.Logger;

import zheezes.eisp.collect.model.SummatorDailyFrozenCollectTaskHandler;
import zheezes.eisp.data.orm.CollectTask;
import zheezes.eisp.data.orm.Concentrator;
import zheezes.eisp.data.orm.Summator;
import zheezes.eisp.data.orm.SummatorDailyFrozenData;
import zheezes.protocol.Frame;
import zheezes.protocol.impl.gd.Ctrl12Frame;
import zheezes.protocol.impl.gd.Ctrl92Frame;
import zheezes.protocol.impl.gd.GdConAddr;
import zheezes.protocol.impl.gd.bean.AbstractMeterData;
import zheezes.protocol.impl.gd.bean.MeterData;
import zheezes.protocol.impl.gd.bean.SimpleMeterData;
import zheezes.socket.Transput;
import zheezes.util.ArrayUtil;


public class GdSummatorDailyFrozenCollectTaskHandler extends SummatorDailyFrozenCollectTaskHandler {
	private static Logger logger = Logger.getLogger(GdSummatorDailyFrozenCollectTaskHandler.class);
	
	static {
		logger.debug("loading");
	}
	
	public void run() {
		Calendar cal = Calendar.getInstance();
		cal.setTime(task.getDataDate());		
		Concentrator con = dataAccessor.getConById(task.getConId());
		Summator sm = dataAccessor.getSummatorByCon(con.getId());
		if(dataAccessor.querySummatorDailyFrozenDataByMpIdAndDate(sm.getMpId(), cal.getTime()) == null) {
			Ctrl12Frame frame = new Ctrl12Frame();
			frame.setRtua(new GdConAddr(con.getLogicAddr()));
			short option = 0x4001;
			short start = 1;
			short amount = 1;
			frame.setOption(option);
			frame.setStart(start);
			frame.setAmount(amount);
			frame.setCal(cal);
			
			Transput transput;
			if ((transput = postOffice.send(frame)) != null) {
				Frame[] recv = null;
				if (transput.await() == Transput.SUCCESS && (recv = transput.getRecv()) != null) {
					task.setCommSuccNum(task.getCommSuccNum() + 1);
					// Object message = null;
					for (Frame message : recv) {
						// while((message = mailbox.get()) != null) {
						if (message instanceof Ctrl92Frame) {
							Ctrl92Frame f = (Ctrl92Frame) message;
							if (frame.match(f)) {
								if (save(sm, f) == 0) {
									task.setStatus(CollectTask.STATUS_FINISH);
									checkSummatorDailyUse(sm, cal);
								}	
							} else {
								logger.warn(String.format("frame is not match when collect summator daily frozen data"));
								logger.warn(String.format("request frame[%d]:%s", frame.getFseq(), ArrayUtil.sprintf(frame.getBytes(), "%02X ")));
								logger.warn(String.format("request frame[%d]:%s", f.getFseq(), ArrayUtil.sprintf(f.getBytes(), "%02X ")));
							}
						}
					}
				}
			}
			task.setRunTimes(task.getRunTimes() + 1);
		} else {
			task.setStatus(CollectTask.STATUS_FINISH);
		}
		if(!terminated) {
			task.setLastRunDate(Calendar.getInstance().getTime());
		}
		dataAccessor.updateCollectTask(task);
	}

	private int save(Summator sm, Ctrl92Frame rfrm) {
		for (MeterData mdb : rfrm.getMetersData()) {
			AbstractMeterData amd = mdb.getData();
			if (amd instanceof SimpleMeterData) {
				SimpleMeterData smd = (SimpleMeterData) amd;
				SummatorDailyFrozenData smdf = new SummatorDailyFrozenData();
				smdf.setMpId(sm.getMpId());
				smdf.setDate(task.getDataDate());
				smdf.setPp(smd.getValue());
				if (dataAccessor.saveSummatorDailyFrozenData(smdf) == 0) {
					return 0;
				} else {
					logger.info("save resisdent failure");
				}
			}
		}
		return -1;
	}
}
